package com.jfinal.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.jfinal.demo.model.ShoolInfoDao;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

/**
 * 数据源配置
 */
@Configuration
public class JfinalActiveRecordConfig {
    /**
     * 主数据源名称
     */
    private static final String MAIN_DATA_SOURCE_CONFIG = "main";



    @Bean
    @ConfigurationProperties("spring.datasource.main")
    public DruidDataSource masterDataSource(){
        return new DruidDataSource();
    }


    /**
     * 主数据源
     * @return
     */
    @Bean
    public ActiveRecordPlugin initMainActiveRecord() {
        ActiveRecordPlugin arp = new ActiveRecordPlugin(MAIN_DATA_SOURCE_CONFIG, masterTransactionAwareDataSourceProxy());

        arp.addMapping("shool_info", ShoolInfoDao.class);

        arp.start();

        return arp;
    }


    /**
     * 设置数据源代理
     */
    @Bean
    public TransactionAwareDataSourceProxy masterTransactionAwareDataSourceProxy() {
        TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy();
        transactionAwareDataSourceProxy.setTargetDataSource(masterDataSource());
        return transactionAwareDataSourceProxy;
    }



    /**
     * 设置事务管理
     */
    @Bean(name="mainDataSourceTransactionManager")
    public DataSourceTransactionManager masterDataSourceTransactionManager() {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(masterTransactionAwareDataSourceProxy());
        return dataSourceTransactionManager;
    }

}
